

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="CodeHope">
  <meta name="author" content="CodeHope">
  <meta name="keywords" content="希望">
  <title>SpringBoot 接收请求参数相关 - CodeHope</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      
        
          
          
          
        
        <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.22.0/themes/prism-tomorrow.min.css" />
      
      
        <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.22.0/plugins/line-numbers/prism-line-numbers.min.css" />
      
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"quancundexiwang.wang","root":"/","version":"1.8.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":true,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"onlypost":true},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"Mi65hxq7VAFUDwOLeIGAOgiV-gzGzoHsz","app_key":"hMuhiD4FRqhns4giqLiEH9HG","server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.3.0"></head>


<body>
  <header style="height: 80vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>CodeHope</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                村头
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                我
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('http://qiniuyun.quancundexiwang.wang/20210502162555.png') repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="SpringBoot 接收请求参数相关">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-05-08 19:05" pubdate>
        2021年5月8日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.1k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      41
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
            <div class="scroll-down-bar">
              <i class="iconfont icon-arrowdown"></i>
            </div>
          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">SpringBoot 接收请求参数相关</h1>
            
            <div class="markdown-body">
              <p>SpringBoot 接收请求参数相关</p>
<h2 id="1-URL中的参数查询"><a href="#1-URL中的参数查询" class="headerlink" title="1. URL中的参数查询"></a>1. URL中的参数查询</h2><h3 id="a-xxxxx-id-类型"><a href="#a-xxxxx-id-类型" class="headerlink" title="a) xxxxx/id 类型"></a>a) xxxxx/id 类型</h3><p>一般这样的请求的URL是酱紫的==&gt;<code>/api/v1/queryOrder/1</code></p>
<p>那么我们的控制器如何拿到这种URL中的参数呢？</p>
<p><code>OrderController.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>codehope<span class="token punctuation">.</span>ch<span class="token punctuation">.</span>controllers<span class="token punctuation">.</span>api<span class="token punctuation">.</span>v1</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>web<span class="token punctuation">.</span>bind<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span></span><span class="token class-name">GetMapping</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>web<span class="token punctuation">.</span>bind<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span></span><span class="token class-name">PathVariable</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>web<span class="token punctuation">.</span>bind<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span></span><span class="token class-name">RestController</span><span class="token punctuation">;</span>

<span class="token annotation punctuation">@RestController</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">OrderController</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/queryOrder/&#123;id&#125;"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">queryOrderById</span><span class="token punctuation">(</span><span class="token annotation punctuation">@PathVariable</span> <span class="token class-name">String</span> id<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><code>@PathVariable</code>顾名思义~路径变量可以取出URL中的参数变量，默认按名字去匹配，也可以通过设置<code>name</code>去匹配</p>
<p><img src="http://qiniuyun.quancundexiwang.wang/image-20210502215329942.png" srcset="/img/loading.gif" alt="image-20210502215329942"></p>
<p>测试访问 <a target="_blank" rel="noopener" href="http://localhost:8080/api/v1/queryOrder/1">http://localhost:8080/api/v1/queryOrder/1</a></p>
<p><img src="http://qiniuyun.quancundexiwang.wang/image-20210502215431830.png" srcset="/img/loading.gif" alt="image-20210502215431830"></p>
<h3 id="b-xxx-name-ch-amp-age-23类型"><a href="#b-xxx-name-ch-amp-age-23类型" class="headerlink" title="b) xxx?name=ch&amp;age=23类型"></a>b) xxx?name=ch&amp;age=23类型</h3><p>一般这样的请求URL=&gt; <code>/api/v1/queryOrderByParams?OrderName=Peck&amp;orderId=1</code>,在写前端的时候这种一般为URL的参数Param,所以在这里使用<code>@RequestParam</code>注解来对参数进行接收！</p>
<p><code>OrderController.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/queryOrderByParams"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">queryOrderByParams</span><span class="token punctuation">(</span><span class="token annotation punctuation">@RequestParam</span> <span class="token class-name">String</span> <span class="token class-name">OrderName</span><span class="token punctuation">,</span> <span class="token annotation punctuation">@RequestParam</span> <span class="token class-name">String</span> orderId<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    
    <span class="token keyword">return</span> <span class="token class-name">OrderName</span> <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span>orderId<span class="token punctuation">;</span>
    
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/image-20210502220256987.png" srcset="/img/loading.gif"></p>
<p>接收数组类型的数据</p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/queryOrderByParams"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">queryOrderByParams</span><span class="token punctuation">(</span><span class="token annotation punctuation">@RequestParam</span> <span class="token class-name">String</span> <span class="token class-name">OrderName</span><span class="token punctuation">,</span> <span class="token annotation punctuation">@RequestParam</span> <span class="token class-name">String</span> orderId<span class="token punctuation">,</span> <span class="token annotation punctuation">@RequestParam</span> <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> tags<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">StringBuilder</span> sum <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">String</span> tag <span class="token operator">:</span> tags<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        tag <span class="token operator">=</span> tag <span class="token operator">+</span> <span class="token string">","</span><span class="token punctuation">;</span>
        sum<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>tag<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token class-name">OrderName</span> <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> orderId <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> sum<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/image-20210502221017135.png" srcset="/img/loading.gif" alt="image-20210502221017135"></p>
<h2 id="2-请求体中参数-RequestBody查询"><a href="#2-请求体中参数-RequestBody查询" class="headerlink" title="2. 请求体中参数@RequestBody查询"></a>2. 请求体中参数<code>@RequestBody</code>查询</h2><p>这种一般常见于Post请求！传递<code>json</code>数据！</p>
<h3 id="方式1：定义DTO接收"><a href="#方式1：定义DTO接收" class="headerlink" title="方式1：定义DTO接收"></a>方式1：定义DTO接收</h3><p>比如创建订单的时候！需要商品id，商品名称，商品价格，创建时间等最基础的字段<del>我们一般在java里面将这些字段放入一个DTO类！也可以称之为一个bean</del> DTO(data transition object)数据传输对象</p>
<p><code>OrderDto.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>codehope<span class="token punctuation">.</span>ch<span class="token punctuation">.</span>dto</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">Getter</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">Setter</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">ToString</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span><span class="token class-name">Date</span><span class="token punctuation">;</span>

<span class="token annotation punctuation">@Setter</span>
<span class="token annotation punctuation">@Getter</span>
<span class="token annotation punctuation">@ToString</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">OrderDto</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">private</span> <span class="token class-name">Integer</span> product_id<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> product_name<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> order_date<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><code>OrderController.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@PostMapping</span><span class="token punctuation">(</span><span class="token string">"/createOrder"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">OrderDto</span> <span class="token function">createOrder</span><span class="token punctuation">(</span><span class="token annotation punctuation">@RequestBody</span> <span class="token class-name">OrderDto</span> orderDto<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span> orderDto<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/image-20210502222603427.png" srcset="/img/loading.gif" alt="image-20210502222603427"></p>
<h3 id="方式2：Map接收（不常用）"><a href="#方式2：Map接收（不常用）" class="headerlink" title="方式2：Map接收（不常用）"></a>方式2：Map接收（不常用）</h3><blockquote>
<p>为什么不常用，我们有时候复杂对象（多层嵌套的话，对一些字段的处理，需要层层的去取！而且基本数据类型，是存在一个装箱的过程 ，我们要尽量的避免频繁的拆箱，装箱的。）</p>
</blockquote>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@PostMapping</span><span class="token punctuation">(</span><span class="token string">"/createOrder"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Object</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> <span class="token function">createOrder</span><span class="token punctuation">(</span><span class="token annotation punctuation">@RequestBody</span> <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Object</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> map<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>map<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> map<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210505094431.png" srcset="/img/loading.gif" alt="image-20210505094423036"></p>
<h2 id="3-使用Validation校验请求的参数"><a href="#3-使用Validation校验请求的参数" class="headerlink" title="3. 使用Validation校验请求的参数"></a>3. 使用Validation校验请求的参数</h2><h3 id="a）准备工作"><a href="#a）准备工作" class="headerlink" title="a）准备工作"></a>a）准备工作</h3><p>引入相关依赖</p>
<div class="code-wrapper"><pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>org.springframework.boot<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>spring-boot-starter-validation<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre></div>
<h3 id="b）基本校验注解"><a href="#b）基本校验注解" class="headerlink" title="b）基本校验注解"></a>b）基本校验注解</h3><p><img src="http://qiniuyun.quancundexiwang.wang/20210505121144.png" srcset="/img/loading.gif" alt="image-20210505121142961"></p>
<p>拿出错误抛出的异常信息！</p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210505121240.png" srcset="/img/loading.gif" alt="image-20210505121239507"></p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210505121358.png" srcset="/img/loading.gif" alt="image-20210505121357425"></p>
<p>还有更多其他的基本注解，在以后的项目中可能经常用到</p>
 <p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【空检查】</p>

<ul>
<li><p><code>@Null</code>验证对象是否为null</p>
</li>
<li><p><code>@NotNull</code>验证对象是否不为null, 无法查检长度为0的字符串</p>
</li>
<li><p><code>@NotBlank</code> 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.</p>
</li>
<li><p><code>@NotEmpty</code>检查约束元素是否为NULL或者是EMPTY. </p>
<p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【Booelan检查】</p>
</li>
<li><p><code>@AssertTrue</code>    验证 Boolean 对象是否为 true  </p>
</li>
<li><p><code>@AssertFalse</code>    验证 Boolean 对象是否为 false  </p>
<p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【长度检查】</p>
</li>
<li><p><code>@Size(min=, max=)</code>长度检查（Array,Collection,Map,String）长度是否在给定的范围之内  </p>
</li>
<li><p><code>@Length(min=, max=)</code>验证注解的元素值长度在min和max区间内</p>
<p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【日期检查】</p>
</li>
<li><p><code>@Past</code>    验证 Date 和 Calendar 对象是否在当前时间之前  </p>
</li>
<li><p><code>@Future</code>    验证 Date 和 Calendar 对象是否在当前时间之后  </p>
</li>
<li><p><code>@Pattern</code>  验证 String 对象是否符合正则表达式的规则</p>
<p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【数值检查】</p>

</li>
</ul>
<blockquote>
<p>建议使用在Stringng,Integer类型，不建议使用在int类型上，因为表单值为“”时无法转换为int，但可以转换为Stirng为””,Integer为null</p>
</blockquote>
<ul>
<li><code>@Min</code>            验证 Number 和 String 对象是否大等于指定的值  </li>
<li><code>@Max</code>            验证 Number 和 String 对象是否小等于指定的值  </li>
<li><code>@Digits</code>            验证 Number 和 String 的构成是否合法  </li>
<li><code>@Digits(integer=,fraction=)</code>        验证字符串是否是符合指定格式的数字，interger指定整数精度，fraction指定小数精度。</li>
<li><code>@Range(min=, max=)</code>    验证注解的元素值在最小值和最大值间<code>@Range(min=10000,max=50000,message=&quot;range.bean.wage&quot;)</code></li>
<li><code>@DecimalMax</code>  被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度</li>
<li><code>@DecimalMin</code>. 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度</li>
</ul>
<h3 id="c）验证DTO复杂的Java-bean"><a href="#c）验证DTO复杂的Java-bean" class="headerlink" title="c）验证DTO复杂的Java bean"></a>c）验证DTO复杂的<code>Java bean</code></h3><p>比如一个接口，接收一个<code>bean</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@PostMapping</span><span class="token punctuation">(</span><span class="token string">"/createOrder"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">createOrder</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Validated</span> <span class="token annotation punctuation">@RequestBody</span> <span class="token class-name">OrderDto</span> orderDto<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>orderDto<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token string">"创建订单成功！"</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>我们此时可以在bean类中的成员变量上进行一些限制</p>
<p><code>OrderDto.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>dto</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">Getter</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">Setter</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">ToString</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>hibernate<span class="token punctuation">.</span>validator<span class="token punctuation">.</span>constraints<span class="token punctuation">.</span></span><span class="token class-name">Length</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span>constraints<span class="token punctuation">.</span></span><span class="token class-name">Min</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span>constraints<span class="token punctuation">.</span></span><span class="token class-name">NotEmpty</span><span class="token punctuation">;</span>

<span class="token annotation punctuation">@Getter</span>
<span class="token annotation punctuation">@Setter</span>
<span class="token annotation punctuation">@ToString</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">OrderDto</span> <span class="token punctuation">&#123;</span>
  <span class="token comment">//字符串一般用length比较好</span>
    <span class="token annotation punctuation">@Length</span><span class="token punctuation">(</span>max <span class="token operator">=</span> <span class="token number">255</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> product_name<span class="token punctuation">;</span>
    <span class="token annotation punctuation">@Min</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> <span class="token class-name">Long</span> order_no<span class="token punctuation">;</span>
    <span class="token annotation punctuation">@NotEmpty</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> order_date<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>测试</p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210505150458.png" srcset="/img/loading.gif" alt="image-20210505150457060"></p>
 <p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【校验bean的参数，需要加@Validated】</p>

<h3 id="d）多层级bean的校验-Valid"><a href="#d）多层级bean的校验-Valid" class="headerlink" title="d）多层级bean的校验@Valid"></a>d）多层级bean的校验<code>@Valid</code></h3><p>比如上面接收的那个bean中！其中某个字段还是一个bean，然后也要保证里面的一些字段是满足一定要求的那么就使用<code>@Valid</code>注解</p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210505153749.png" srcset="/img/loading.gif" alt="image-20210505153747456"></p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210505153958.png" srcset="/img/loading.gif" alt="image-20210505153957126"></p>
<p>这里遇到的其实是有个小问题的，对于判断空值，不同的数据类型需要使用不同的注解</p>
<p>推荐</p>
<ul>
<li><p><code>@NotEmpty</code> 用在集合类上面</p>
</li>
<li><p><code>@NotBlank</code> 用在String上面</p>
</li>
<li><p><code>@NotNull</code>   用在基本类型上</p>
</li>
</ul>
<h3 id="e）-Valid和-Validated的区别"><a href="#e）-Valid和-Validated的区别" class="headerlink" title="e） @Valid和@Validated的区别"></a>e） <code>@Valid</code>和<code>@Validated</code>的区别</h3><h4 id="1-注解位置："><a href="#1-注解位置：" class="headerlink" title="1.注解位置："></a>1.注解位置：</h4><p><code>@Validated</code>：用在类型、方法和方法参数上。但不能用于成员属性（field）</p>
<p><code>@Valid</code>：可以用在方法、构造函数、方法参数和成员属性（field）上</p>
<h4 id="2-分组校验"><a href="#2-分组校验" class="headerlink" title="2.分组校验"></a>2.分组校验</h4><p><code>@Validated</code>：提供分组功能，可以在参数验证时，根据不同的分组采用不同的验证机制</p>
<p><code>@Valid</code>：没有分组功能</p>
<h2 id="4-自定义校验注解"><a href="#4-自定义校验注解" class="headerlink" title="4. 自定义校验注解"></a>4. 自定义校验注解</h2><h3 id="a）分析"><a href="#a）分析" class="headerlink" title="a）分析"></a>a）分析</h3><blockquote>
<p>上面都是一些简单的基本的注解，对数据进行基本的验证，如果只用基础注解来做项目！也不是不可以但是有的业务场景可能会比较麻烦，那么我们就需要根据我们的业务来做一些定制化的注解，比如输入的两次密码是否相同！某一种字符串是否满足你的特殊的要求等等。 那么我们此时就可以学习如何去自定义一个校验的注解</p>
</blockquote>
<h3 id="b）开发"><a href="#b）开发" class="headerlink" title="b）开发"></a>b）开发</h3><p>那么我们就结合着注册过程需要输入两次相同的密码！才给他通过注册的验证，那么首先先给一个注册提交信息的DTO的类</p>
<p><code>RegisterUserInfoDto.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>dto</span><span class="token punctuation">;</span>


<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">Getter</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">Setter</span><span class="token punctuation">;</span>

<span class="token annotation punctuation">@Setter</span>
<span class="token annotation punctuation">@Getter</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RegisterUserInfoDto</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> username<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token class-name">String</span> password<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token class-name">String</span> rePassword<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token class-name">String</span> nickName<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>然后我们可以使用自定义的校验注解，去判断这个dto中的``password<code>和</code>rePassword`是否相同，来决定是不是给他通过验证！</p>
<p><code>PasswordIsEqual.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>customValid</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">Constraint</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">Payload</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span></span><span class="token operator">*</span><span class="token punctuation">;</span>

<span class="token annotation punctuation">@Retention</span><span class="token punctuation">(</span><span class="token class-name">RetentionPolicy</span><span class="token punctuation">.</span>RUNTIME<span class="token punctuation">)</span>
<span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token punctuation">&#123;</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@Documented</span>
<span class="token annotation punctuation">@Constraint</span><span class="token punctuation">(</span>validatedBy <span class="token operator">=</span> <span class="token class-name">PasswordIsEqualValidator</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">PasswordIsEqual</span> <span class="token punctuation">&#123;</span>

    <span class="token comment">//传递不同过的message</span>
    <span class="token class-name">String</span> <span class="token function">message</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token string">"passwords are not equal"</span><span class="token punctuation">;</span>

    <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">groups</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>

    <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">extends</span> <span class="token class-name">Payload</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">payload</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>我们知道注解呢～只是起到了标识的作用，到最后还是需要有一个类来做业务的处理的，这里的<code>PasswordIsEqualValidator</code>就是用来处理注解表示的那个dto对象的业务验证的。</p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210506174746.png" srcset="/img/loading.gif" alt="image-20210506174739081"></p>
<p><code>PasswordIsEqualValidator.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>customValid</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>dto<span class="token punctuation">.</span></span><span class="token class-name">RegisterUserInfoDto</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">ConstraintValidator</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">ConstraintValidatorContext</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">PasswordIsEqualValidator</span> <span class="token keyword">implements</span> <span class="token class-name">ConstraintValidator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">PasswordIsEqual</span><span class="token punctuation">,</span> <span class="token class-name">RegisterUserInfoDto</span><span class="token punctuation">></span></span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">isValid</span><span class="token punctuation">(</span><span class="token class-name">RegisterUserInfoDto</span> registerUserInfoDto<span class="token punctuation">,</span> <span class="token class-name">ConstraintValidatorContext</span> constraintValidatorContext<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> password <span class="token operator">=</span> registerUserInfoDto<span class="token punctuation">.</span><span class="token function">getPassword</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> rePassword <span class="token operator">=</span> registerUserInfoDto<span class="token punctuation">.</span><span class="token function">getRePassword</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>password<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>rePassword<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> password<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>rePassword<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210506175156.png" srcset="/img/loading.gif" alt="image-20210506175153703"></p>
<h3 id="c）完整代码"><a href="#c）完整代码" class="headerlink" title="c）完整代码"></a>c）完整代码</h3><p><code>PasswordIsEqualValidator.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>customValid</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>dto<span class="token punctuation">.</span></span><span class="token class-name">RegisterUserInfoDto</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">ConstraintValidator</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">ConstraintValidatorContext</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">PasswordIsEqualValidator</span> <span class="token keyword">implements</span> <span class="token class-name">ConstraintValidator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">PasswordIsEqual</span><span class="token punctuation">,</span> <span class="token class-name">RegisterUserInfoDto</span><span class="token punctuation">></span></span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">isValid</span><span class="token punctuation">(</span><span class="token class-name">RegisterUserInfoDto</span> registerUserInfoDto<span class="token punctuation">,</span> <span class="token class-name">ConstraintValidatorContext</span> constraintValidatorContext<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> password <span class="token operator">=</span> registerUserInfoDto<span class="token punctuation">.</span><span class="token function">getPassword</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> rePassword <span class="token operator">=</span> registerUserInfoDto<span class="token punctuation">.</span><span class="token function">getRePassword</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>password<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>rePassword<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> password<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>rePassword<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><code>PasswordIsEqual.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>customValid</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">Constraint</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">Payload</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span></span><span class="token operator">*</span><span class="token punctuation">;</span>

<span class="token annotation punctuation">@Retention</span><span class="token punctuation">(</span><span class="token class-name">RetentionPolicy</span><span class="token punctuation">.</span>RUNTIME<span class="token punctuation">)</span>
<span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token punctuation">&#123;</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@Documented</span>
<span class="token annotation punctuation">@Constraint</span><span class="token punctuation">(</span>validatedBy <span class="token operator">=</span> <span class="token class-name">PasswordIsEqualValidator</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">PasswordIsEqual</span> <span class="token punctuation">&#123;</span>

    <span class="token comment">//传递不同过的message</span>
    <span class="token class-name">String</span> <span class="token function">message</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token string">"passwords are not equal"</span><span class="token punctuation">;</span>

    <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">groups</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>

    <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">extends</span> <span class="token class-name">Payload</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">payload</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<h3 id="d）测试使用"><a href="#d）测试使用" class="headerlink" title="d）测试使用"></a>d）测试使用</h3><p><code>RegisterUserInfoDto.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>dto</span><span class="token punctuation">;</span>


<span class="token keyword">import</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>customValid<span class="token punctuation">.</span></span><span class="token class-name">PasswordIsEqual</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">Getter</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">Setter</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">lombok<span class="token punctuation">.</span></span><span class="token class-name">ToString</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span>constraints<span class="token punctuation">.</span></span><span class="token class-name">NotNull</span><span class="token punctuation">;</span>

<span class="token annotation punctuation">@Setter</span>
<span class="token annotation punctuation">@Getter</span>
<span class="token annotation punctuation">@ToString</span>
<span class="token annotation punctuation">@PasswordIsEqual</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RegisterUserInfoDto</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@NotNull</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> username<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@NotNull</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> password<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@NotNull</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> rePassword<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@NotNull</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> nickName<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>然后新的注册接口接收<code>RegisterUserInfoDto</code> bean作为请求体对象</p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@RestController</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">UserController</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@PostMapping</span><span class="token punctuation">(</span><span class="token string">"/registerNewUser"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">registerNewUser</span><span class="token punctuation">(</span><span class="token annotation punctuation">@RequestBody</span> <span class="token annotation punctuation">@Validated</span> <span class="token class-name">RegisterUserInfoDto</span> registerUserInfoDto<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>registerUserInfoDto<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token string">"1"</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210506181457.png" srcset="/img/loading.gif" alt="image-20210506181455391"></p>
<p>可以看到已经校验成功了！并且返回给了前端对应的信息！</p>
<h2 id="5-自定义校验注解的参数获取"><a href="#5-自定义校验注解的参数获取" class="headerlink" title="5.自定义校验注解的参数获取"></a>5.自定义校验注解的参数获取</h2><h3 id="a）从哪获取"><a href="#a）从哪获取" class="headerlink" title="a）从哪获取"></a>a）从哪获取</h3><p>实现<code>ConstraintValidator</code>接口的<code>initialize</code>方法</p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508151329.png" srcset="/img/loading.gif"></p>
<h3 id="b）案例：校验密码的长度"><a href="#b）案例：校验密码的长度" class="headerlink" title="b）案例：校验密码的长度"></a>b）案例：校验密码的长度</h3><p>新增注解参数</p>
<p><code>PasswordIsEqual.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>customValid</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">Constraint</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">Payload</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span></span><span class="token operator">*</span><span class="token punctuation">;</span>

<span class="token annotation punctuation">@Retention</span><span class="token punctuation">(</span><span class="token class-name">RetentionPolicy</span><span class="token punctuation">.</span>RUNTIME<span class="token punctuation">)</span>
<span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token punctuation">&#123;</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@Documented</span>
<span class="token annotation punctuation">@Constraint</span><span class="token punctuation">(</span>validatedBy <span class="token operator">=</span> <span class="token class-name">PasswordIsEqualValidator</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">PasswordIsEqual</span> <span class="token punctuation">&#123;</span>

    <span class="token comment">//传递不同过的message</span>
    <span class="token class-name">String</span> <span class="token function">message</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token string">"密码不符合规范！"</span><span class="token punctuation">;</span>

    <span class="token keyword">int</span> <span class="token function">min</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token number">5</span><span class="token punctuation">;</span>

    <span class="token keyword">int</span> <span class="token function">max</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token number">11</span><span class="token punctuation">;</span>

    <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">groups</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>

    <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">extends</span> <span class="token class-name">Payload</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">payload</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508151711.png" srcset="/img/loading.gif"></p>
<p><code>PasswordIsEqualValidator.java</code></p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>customValid</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">com<span class="token punctuation">.</span>code<span class="token punctuation">.</span>hope<span class="token punctuation">.</span>dto<span class="token punctuation">.</span></span><span class="token class-name">RegisterUserInfoDto</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">ConstraintValidator</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span><span class="token class-name">ConstraintValidatorContext</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">PasswordIsEqualValidator</span> <span class="token keyword">implements</span> <span class="token class-name">ConstraintValidator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">PasswordIsEqual</span><span class="token punctuation">,</span> <span class="token class-name">RegisterUserInfoDto</span><span class="token punctuation">></span></span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">private</span> <span class="token keyword">int</span> max<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token keyword">int</span> min<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">initialize</span><span class="token punctuation">(</span><span class="token class-name">PasswordIsEqual</span> constraintAnnotation<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>max <span class="token operator">=</span> constraintAnnotation<span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>min <span class="token operator">=</span> constraintAnnotation<span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">ConstraintValidator</span><span class="token punctuation">.</span><span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">initialize</span><span class="token punctuation">(</span>constraintAnnotation<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">isValid</span><span class="token punctuation">(</span><span class="token class-name">RegisterUserInfoDto</span> registerUserInfoDto<span class="token punctuation">,</span> <span class="token class-name">ConstraintValidatorContext</span> constraintValidatorContext<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> password <span class="token operator">=</span> registerUserInfoDto<span class="token punctuation">.</span><span class="token function">getPassword</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> rePassword <span class="token operator">=</span> registerUserInfoDto<span class="token punctuation">.</span><span class="token function">getRePassword</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//比较长度是否合法</span>
        <span class="token keyword">boolean</span> isLegalLength <span class="token operator">=</span> password<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">>=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>min <span class="token operator">&amp;&amp;</span> password<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>max<span class="token punctuation">;</span>
        <span class="token comment">//比较两次密码是否相同</span>
        <span class="token keyword">boolean</span> isEqual <span class="token operator">=</span> password<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>rePassword<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> isLegalLength <span class="token operator">&amp;&amp;</span> isEqual<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>


<p><img src="http://qiniuyun.quancundexiwang.wang/20210508152609.png" srcset="/img/loading.gif"></p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508152740.png" srcset="/img/loading.gif" alt="image-20210508152737415"></p>
<h2 id="6-优化参数校验的异常捕获"><a href="#6-优化参数校验的异常捕获" class="headerlink" title="6. 优化参数校验的异常捕获"></a>6. 优化参数校验的异常捕获</h2><h3 id="a）分析-1"><a href="#a）分析-1" class="headerlink" title="a）分析"></a>a）分析</h3><p>上面我们看到的异常信息，过于繁杂，包含太多的对于前端或者客户无用的信息，因为我们是通过最基层的异常类<code>Exception</code>直接获取<code>message</code>抛出的,</p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508160448.png" srcset="/img/loading.gif" alt="image-20210508160447429"></p>
<p>不夸张的说，可能只有我们后端开发人员可以看懂，那么我们这一章就根据参数可能抛出的异常进行更细节的处理</p>
<h3 id="b-Bean参数字段校验异常"><a href="#b-Bean参数字段校验异常" class="headerlink" title="b) Bean参数字段校验异常"></a>b) Bean参数字段校验异常</h3><blockquote>
<p><code>MethodArgumentNotValidException</code>通常bean作为参数，其中某些字段校验不通过抛出此类异常</p>
</blockquote>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508160624.png" srcset="/img/loading.gif" alt="image-20210508160623470"></p>
<p>可以从上面控制台输出看出报错类型，然后我们再全局的异常捕获中，增加一种错误的拦截就可以了</p>
<p>模拟多个参数错误的校验</p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508162156.png" srcset="/img/loading.gif" alt="image-20210508162154891"></p>
<p><code>GlobalException.java</code>新增的错误拦截器代码片段</p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@ExceptionHandler</span><span class="token punctuation">(</span><span class="token class-name">MethodArgumentNotValidException</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">ExceptionUnifyDto</span> <span class="token function">handleMethodArgumentNotValidException</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> response<span class="token punctuation">,</span> <span class="token class-name">MethodArgumentNotValidException</span> methodArgumentNotValidException<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">String</span> uri <span class="token operator">=</span> <span class="token function">concatMethodURI</span><span class="token punctuation">(</span>request<span class="token punctuation">,</span> response<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">final</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">ObjectError</span><span class="token punctuation">></span></span> allErrors <span class="token operator">=</span> methodArgumentNotValidException<span class="token punctuation">.</span><span class="token function">getBindingResult</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getAllErrors</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> message <span class="token operator">=</span> <span class="token function">concatErrorMessage</span><span class="token punctuation">(</span>allErrors<span class="token punctuation">)</span><span class="token punctuation">;</span>
    response<span class="token punctuation">.</span><span class="token function">setStatus</span><span class="token punctuation">(</span><span class="token number">400</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    exceptionUnifyDto<span class="token punctuation">.</span><span class="token function">setCode</span><span class="token punctuation">(</span><span class="token number">10001</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    exceptionUnifyDto<span class="token punctuation">.</span><span class="token function">setMessage</span><span class="token punctuation">(</span>message<span class="token punctuation">)</span><span class="token punctuation">;</span>
    exceptionUnifyDto<span class="token punctuation">.</span><span class="token function">setUri</span><span class="token punctuation">(</span>uri<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> exceptionUnifyDto<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">private</span> <span class="token class-name">String</span> <span class="token function">concatErrorMessage</span><span class="token punctuation">(</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">ObjectError</span><span class="token punctuation">></span></span> allErrors<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">StringBuilder</span> errMessage <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span><span class="token string">" "</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">ObjectError</span> allError <span class="token operator">:</span> allErrors<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        errMessage<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>allError<span class="token punctuation">.</span><span class="token function">getDefaultMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span><span class="token string">","</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> errMessage<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508162658.png" srcset="/img/loading.gif" alt="image-20210508162657714"></p>
<p>测试使用！</p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508162924.png" srcset="/img/loading.gif" alt="image-20210508162923090"></p>
<h3 id="c-URL中参数校验异常"><a href="#c-URL中参数校验异常" class="headerlink" title="c) URL中参数校验异常"></a>c) URL中参数校验异常</h3><blockquote>
<p><code>ConstraintViolationException</code>通常url中的参数校验不通过，抛出此类异常</p>
</blockquote>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508165650.png" srcset="/img/loading.gif" alt="image-20210508165646997"></p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508165748.png" srcset="/img/loading.gif" alt="image-20210508165747809"></p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508163953.png" srcset="/img/loading.gif" alt="image-20210508163951943"></p>
<p>其实看起来这个错误信息还可以哈！不过里面也是包含了一些多余的信息，【<code>registerNewUser.user_id: </code> 这些也是属于我们代码中的一些信息，就不要返回给前端了】那么我们也是可以通过自定义异常的拦截器，进行一些定制化的开发的。</p>
<p><code>GlobalException.java</code>新增的错误拦截器代码片段</p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@ExceptionHandler</span><span class="token punctuation">(</span><span class="token class-name">ConstraintViolationException</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">ExceptionUnifyDto</span> <span class="token function">handleConstraintViolationException</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> response<span class="token punctuation">,</span> <span class="token class-name">ConstraintViolationException</span> constraintViolationException<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">String</span> uri <span class="token operator">=</span> <span class="token function">concatMethodURI</span><span class="token punctuation">(</span>request<span class="token punctuation">,</span> response<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">StringBuilder</span> messageBuilder <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span><span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">ConstraintViolation</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> constraintViolation <span class="token operator">:</span> constraintViolationException<span class="token punctuation">.</span><span class="token function">getConstraintViolations</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        messageBuilder<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>constraintViolation<span class="token punctuation">.</span><span class="token function">getMessageTemplate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span><span class="token string">","</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>messageBuilder<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    response<span class="token punctuation">.</span><span class="token function">setStatus</span><span class="token punctuation">(</span><span class="token number">400</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    exceptionUnifyDto<span class="token punctuation">.</span><span class="token function">setCode</span><span class="token punctuation">(</span><span class="token number">10001</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    exceptionUnifyDto<span class="token punctuation">.</span><span class="token function">setMessage</span><span class="token punctuation">(</span>messageBuilder<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    exceptionUnifyDto<span class="token punctuation">.</span><span class="token function">setUri</span><span class="token punctuation">(</span>uri<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> exceptionUnifyDto<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508170009.png" srcset="/img/loading.gif" alt="image-20210508170007937"></p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508170032.png" srcset="/img/loading.gif" alt="image-20210508170031147"></p>
<h3 id="d-必传参数缺失异常"><a href="#d-必传参数缺失异常" class="headerlink" title="d) 必传参数缺失异常"></a>d) 必传参数缺失异常</h3><blockquote>
<p><code>MissingServletRequestParameterException</code>通常出现在缺少一些必传参数时所抛出的异常！</p>
</blockquote>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508170353.png" srcset="/img/loading.gif" alt="image-20210508170352288"></p>
<p>状态码500+提示信息依然不够规范，也需要全局拦截中单独去处理，不过这种字段传参缺失的问题，一般是给前端开发人员看的，所以返回一些英文字段名也是没有问题的</p>
<div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@ExceptionHandler</span><span class="token punctuation">(</span><span class="token class-name">MissingServletRequestParameterException</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">ExceptionUnifyDto</span> <span class="token function">handleMissingServletRequestParameterException</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> response<span class="token punctuation">,</span> <span class="token class-name">MissingServletRequestParameterException</span> missingServletRequestParameterException<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">String</span> uri <span class="token operator">=</span> <span class="token function">concatMethodURI</span><span class="token punctuation">(</span>request<span class="token punctuation">,</span> response<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> message <span class="token operator">=</span> missingServletRequestParameterException<span class="token punctuation">.</span><span class="token function">getParameterName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">"不能为空！"</span><span class="token punctuation">;</span>
    response<span class="token punctuation">.</span><span class="token function">setStatus</span><span class="token punctuation">(</span><span class="token number">400</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    exceptionUnifyDto<span class="token punctuation">.</span><span class="token function">setCode</span><span class="token punctuation">(</span><span class="token number">10001</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    exceptionUnifyDto<span class="token punctuation">.</span><span class="token function">setMessage</span><span class="token punctuation">(</span>message<span class="token punctuation">)</span><span class="token punctuation">;</span>
    exceptionUnifyDto<span class="token punctuation">.</span><span class="token function">setUri</span><span class="token punctuation">(</span>uri<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> exceptionUnifyDto<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508171636.png" srcset="/img/loading.gif" alt="image-20210508171635996"></p>
<p><img src="http://qiniuyun.quancundexiwang.wang/20210508171657.png" srcset="/img/loading.gif" alt="image-20210508171656373"></p>
<p>那么参数校验相关的各种基础知识就总结到这里，希望以后的学习能积累更多的知识！</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/Java/">Java</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/SpringBoot%E5%9F%BA%E7%A1%80/">SpringBoot基础</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/posts/41906/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">原生JS操作cookie</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/posts/22266/">
                        <span class="hidden-mobile">SpringBoot控制器自动根据所在目录配置prefix</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script type="text/javascript">
    Fluid.utils.waitElementVisible('vcomments', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "Mi65hxq7VAFUDwOLeIGAOgiV-gzGzoHsz",
          app_key: "hMuhiD4FRqhns4giqLiEH9HG",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: false,
          recordIP: false,
          serverURLs: "",
        });
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the
    <a target="_blank" href="https://valine.js.org" rel="nofollow noopener noopener">comments powered by Valine.</a>
  </noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    

  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        豫ICP备20009912号-1
      </a>
    </span>
    
  </div>


  
</footer>

<!-- SCRIPTS -->

  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":true,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    
      <script  src="/js/lazyload.js" ></script>
    
  



  
    
  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.0/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "http://qiniuyun.quancundexiwang.wang/xmlSearch.xml";
      var inputArea = document.querySelector("#local-search-input");
      inputArea.onclick = function () {
        searchFunc(path, 'local-search-input', 'local-search-result');
        this.onclick = null
      }
    })()
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>



</body>
</html>
